<?php
/** 
 * 敏感词的操作
 *铭感词列表的获取 | 敏感词的过滤
 * @author susy.liang <liangling@ilongyuan.com.cn> 
 */

namespace Api\Event;

class SensitiveEvent extends BaseEvent 
{	
	/**
	*Mongo集合的实例化
	*/
	protected $serviceObj = '';

	/**
	*参数初始化
	*/
	protected function _initialize(){
		parent::_initialize();

	}

	/** 
	 * 敏感词列表信息获取
	 * @return array
	* @author susy.liang
	*/
	public function lists()
	{
		if(F('Sensitive'))
			return F('Sensitive');

		$keywords = $this->keywordCache();
		
		return $keywords;
	}

	/**
	*关键字缓存
	*/
	public function keywordCache($new = array()){
		$keywords = array();

		if ($new && !F('Sensitive'))
		{
			$keywords = F('Sensitive');
			$keywords['keyword'][] = $new['keyword'];
			$keywords['replace'][] = $new['replace'];
		}
		else
		{
			$serviceObj = D('Common/Sensitive', 'Service');
			$field = 'keyword,replace';
			$map = array('status'=>array('egt', 0));
			$resource = $serviceObj->where($map)->field($field)->select();
			if($resource){
				foreach ($resource as $key => $value) {
					$keywords['keyword'][] = $value['keyword'];
					$keywords['replace'][] = $value['replace'];
				}
			}
		}
		$keywords && F('Sensitive', $keywords);
		return $keywords;
	}

	/**
	*敏感词的过滤
	*使用preg_replace 数组模式替换
	*@param string $content 目标内容
	*@author susy<susy.liang@ilongyuan.com.cn>
	*/
	public function censor(&$content){
		$keywords = $this->lists();
		if(!$keywords)
			return true;
		$i = 0;
		$length = 100;
		while($findWords = array_slice($keywords['keyword'], $i, $length)){
			if(empty($findWords))
				break;
			$replaceWords = array_slice($keywords['replace'], $i, $length);
			$replaceWords = array_map('getDefaultReplace', $replaceWords);
			$i += $length;
			$content = str_replace($findWords, $replaceWords, $content);
		}
		return true;
	}


	public function check(&$content)
	{
		$keywords = $this->lists();
		if(!$keywords)
			return true;
		$i = 0;
		$length = 100;
		while($findWords = array_slice($keywords['keyword'], $i, $length)){
			if(empty($findWords))
				break;
			// $replaceWords = array_slice($keywords['replace'], $i, $length);
			// $replaceWords = array_map('getDefaultReplace', $replaceWords);
			$i += $length;
		 	$words = implode('|', $findWords);
		 	$words = addslashes($words);
		 	$matched = preg_match('/'.$words.'/i', $content, $result);  
		 	if ($matched){
		 		return false;
		 	}
		}
		return true;
	}

}